package cn.yzj.utils;

import io.jsonwebtoken.lang.Objects;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;

/**
 * @author gzkemays
 * @since 2021/2/19 20:56
 */
public class StreamUtils {
  /** inputStream Convert to outputStream */
  public static ByteArrayOutputStream inputStreamParseOutputStream(final InputStream in)
      throws IOException {
    final ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
    int ch;
    while ((ch = in.read()) != -1) {
      swapStream.write(ch);
    }
    return swapStream;
  }

  /** outputStream转inputStream */
  public static ByteArrayInputStream outputStreamParseInputStream(final OutputStream out)
      throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos = (ByteArrayOutputStream) out;
    final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
    return swapStream;
  }

  /** inputStream转String */
  public static String parse_String(final InputStream in) throws Exception {
    final ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
    int ch;
    while ((ch = in.read()) != -1) {
      swapStream.write(ch);
    }
    return swapStream.toString();
  }

  /** OutputStream 转 string */
  public static String parseString(final OutputStream out) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos = (ByteArrayOutputStream) out;
    final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
    return swapStream.toString();
  }

  /** String转inputStream */
  public static ByteArrayInputStream parseInputStreamOfString(final String in) throws Exception {
    return new ByteArrayInputStream(in.getBytes());
  }

  /** String 转outputStream */
  public static ByteArrayOutputStream parseOutputStreamOfString(final String in) throws Exception {
    return inputStreamParseOutputStream(parseInputStreamOfString(in));
  }

  /** 合并文件 */
  public static void mergeFile(Path file, Path... chunkFiles) throws IOException {
    if (Objects.isEmpty(chunkFiles)) {
      throw new IllegalArgumentException("分片文件不能为空");
    }
    try (FileChannel fileChannel =
        FileChannel.open(
            file, EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE))) {
      for (Path chunkFile : chunkFiles) {
        try (FileChannel chunkChannel =
            FileChannel.open(chunkFile, EnumSet.of(StandardOpenOption.READ))) {
          chunkChannel.transferTo(0, chunkChannel.size(), fileChannel);
        }
      }
    }
  }

  /** 对文件按照指定大小进行分片，在文件所在目录生成分片后的文件块儿 */
  public static void chunkFile(Path file, long chunkSize) throws IOException {
    if (Files.notExists(file) || Files.isDirectory(file)) {
      throw new IllegalArgumentException("文件不存在:" + file);
    }
    if (chunkSize < 1) {
      throw new IllegalArgumentException("分片大小不能小于1个字节:" + chunkSize);
    }
    // 原始文件大小
    final long fileSize = Files.size(file);
    // 分片数量
    final long numberOfChunk =
        fileSize % chunkSize == 0 ? fileSize / chunkSize : (fileSize / chunkSize) + 1;
    // 原始文件名称
    final String fileName = file.getFileName().toString();
    // 读取原始文件
    try (FileChannel fileChannel = FileChannel.open(file, EnumSet.of(StandardOpenOption.READ))) {
      for (int i = 0; i < numberOfChunk; i++) {
        long start = i * chunkSize;
        long end = start + chunkSize;
        if (end > fileSize) {
          end = fileSize;
        }
        // 分片文件名称
        Path chunkFile = Paths.get(fileName + "-" + (i + 1));
        try (FileChannel chunkFileChannel =
            FileChannel.open(
                file.resolveSibling(chunkFile),
                EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE))) {
          // 返回写入的数据长度
          fileChannel.transferTo(start, end - start, chunkFileChannel);
        }
      }
    }
  }

  public static File multipartFileToFile(MultipartFile file, String customerName)
      throws IOException {
    if (file != null && file.getSize() > 0) {
      File toFile;
      InputStream ins = file.getInputStream();
      if (StringUtils.isNotBlank(customerName)) {
        toFile = new File(customerName);
      } else {
        toFile = new File(String.valueOf(System.currentTimeMillis()));
      }
      inputStreamToFile(ins, toFile);
      ins.close();
      return toFile;
    }
    return null;
  }

  public static File multipartFileToFile(MultipartFile file) throws IOException {
    if (file != null && file.getSize() > 0) {
      File toFile;
      InputStream ins = file.getInputStream();
      toFile = new File(file.getOriginalFilename());
      inputStreamToFile(ins, toFile);
      ins.close();
      return toFile;
    }
    return null;
  }

  public static void inputStreamToFile(InputStream ins, File file) {
    try {
      OutputStream os = new FileOutputStream(file);
      int bytesRead;
      byte[] buffer = new byte[8192];
      while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
        os.write(buffer, 0, bytesRead);
      }
      os.close();
      ins.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
